package com.lanou3g.musicenjoy.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
//  二哥你不讲信用,说好了你不删我就不写的
import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou3g.musicenjoy.R;
import com.lanou3g.musicenjoy.adapter.LeftAdapter;
import com.lanou3g.musicenjoy.entity.Left;
import com.lanou3g.musicenjoy.entity.NewSongListEntity;
import com.lanou3g.musicenjoy.entity.PlayMusicEntity;
import com.lanou3g.musicenjoy.eventbus.MyEvent;
import com.lanou3g.musicenjoy.utils.NoScrollListView;
import com.lanou3g.musicenjoy.volley.VolleySingleton;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by 傅吉东 on 15/10/24.
 */
public class NewLeftFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {

    private LeftAdapter adapter;
    private List<Left.ContentEntity> datas;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private NoScrollListView leftNestedScrollView;
    private RequestQueue queue;
    private ImageView newLeftImageView;
    private ImageView backImageView;
    private FragmentManager manager;
    private int clickPosition;//记录当前点击的位置
    private List<PlayMusicEntity> data = new ArrayList<>();
    private int numOfData;//data的总长度
    private int numOfNow;
    String pic;
    private String id;
    private Bundle bundle;
    private WebView webView;
    private TextView textView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        bundle = getArguments();
        View view = inflater.inflate(R.layout.fragment_left, null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        backImageView = (ImageView) getActivity().findViewById(R.id.backImageView);
        backImageView.setOnClickListener(this);
        newLeftImageView = (ImageView) getActivity().findViewById(R.id.newLeftImageView);
        queue = VolleySingleton.getInstance(getActivity()).getRequestQueue();
        Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.coordinator_toolbar);
        manager = getFragmentManager();
        id = bundle.getString("id");
        collapsingToolbarLayout = (CollapsingToolbarLayout) getActivity().findViewById(R.id.collapsing_toolbar);
        collapsingToolbarLayout.setTitle("乐享音乐");
        collapsingToolbarLayout.setExpandedTitleColor(0x00ffffff);
        collapsingToolbarLayout.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
        collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE);
        leftNestedScrollView = (NoScrollListView) getActivity().findViewById(R.id.leftNestedScrollView);
        leftNestedScrollView.setOnItemClickListener(this);
        adapter = new LeftAdapter(getActivity());
        leftNestedScrollView.setAdapter(adapter);
        String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.diy.gedanInfo&format=json&listid=" + id;
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response != null) {
                    Gson gson = new Gson();
                    Left result = gson.fromJson(response, Left.class);
                    if (result != null) {
                        datas = result.getContent();
                        result.getPic_w700();
                        pic = result.getPic_300();
                        Picasso.with(getActivity()).load(pic).into(newLeftImageView);

                        adapter.initData(datas);
                    }
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);
    }


    @Override
    public void onClick(View v) {
        Log.i("xinxin", "点击了back");
        manager.popBackStackImmediate();
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        getAllUrl(position);

    }

    private void getAllUrl(int position) {
        clickPosition = position;//记录下当前点击的position
        numOfData = datas.size();//设置总长度
        numOfNow = 0;//设置当前完成的长度
        for (int i = 0; i < datas.size(); i++) {//获得所有的Url进行网络数据的拉取
            String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.song.getInfos&format=json&songid=" +
                    datas.get(i).getSong_id() + "&ts=1445399459391&e=SmJtjLwgnuWRzBbIIHeXgNusY1L" +
                    "%2FXZoWyOitaQ3ExdPXWpSPZ0Fras1q%2FLVxivZr&nw=2&fr=sns&ucf=1&res=1&l2p=2943&lpb=&usup=1&lebo=0";
            getInternetData(url, i);//i记录了当前正在解析哪个URL
            Log.i("fffffffffff", url);
            //让data集合拥有跟数据匹配的长度
            PlayMusicEntity playMusicEntity = new PlayMusicEntity();
            data.add(playMusicEntity);
        }

    }
    //网络解析
    private void getInternetData(String url, final int position) {

        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {//成功回调
                //进行解析
                NewSongListEntity entity = JSON.parseObject(s, NewSongListEntity.class);
                if (entity != null) {//解析成功,这是其中一个音乐的播放地址
                    String url = entity.getSongurl().getUrl().get(0).getShow_link();//获得了URL
                    String singerName = datas.get(position).getAuthor();
                    String songName = datas.get(position).getTitle();
                    //设置data的相应位置的数据
                    data.get(position).setUrl(url);
                    data.get(position).setPicUrl(pic);
                    data.get(position).setSingerName(singerName);
                    data.get(position).setSongName(songName);
                    numOfNow++;
                    if (numOfNow >= numOfData) {
                        //所有数据均已加载完成
                        EventBus.getDefault().post(new MyEvent.PassData(data, clickPosition));
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                numOfNow++;
                Log.i("NewSongListFragment", "当前已完成" + numOfNow);

            }
        });
        queue.add(request);
    }


}
